package one;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Description: 找出符合条件的苹果
 *
 * @author xzj
 * @date 2021/1/11 23:36
 * @since JDK 1.8
 */
public class FilterApple {

    /**
     * 策略模式解决
     */
    @FunctionalInterface
    interface AppleFilter {
        boolean filter(Apple apple);
    }

    public static class GreenAnd100WeightFilter implements AppleFilter {

        @Override
        public boolean filter(Apple apple) {
            return ("green".equals(apple.getColor()) && apple.getWeight() == 100);
        }
    }

    /**
     * 策略模式解决
     *
     * @param apples      苹果库存
     * @param appleFilter 相应晒选策略
     * @return 符合的苹果
     */
    public static List<Apple> findApple(List<Apple> apples, AppleFilter appleFilter) {
        List<Apple> list = new ArrayList<>();
        for (Apple apple : apples) {
            if (appleFilter.filter(apple)) {
                list.add(apple);
            }
        }
        return list;
    }

    /**
     * 普通方法
     *
     * @param apples 苹果库存
     * @return 符合的苹果
     */
    public static List<Apple> findGreenApple(List<Apple> apples) {
        List<Apple> list = new ArrayList<>();
        for (Apple apple : apples) {
            if ("green".equals(apple.getColor())) {
                list.add(apple);
            }
        }
        return list;
    }

    /**
     * 小优化的方法
     *
     * @param apples 苹果库存
     * @param color  需要晒选的颜色
     * @return 符合的苹果
     */
    public static List<Apple> findApple(List<Apple> apples, String color) {
        List<Apple> list = new ArrayList<>();
        for (Apple apple : apples) {
            if (color.equals(apple.getColor())) {
                list.add(apple);
            }
        }
        return list;
    }

    public static void main(String[] args) {
        List<Apple> list = Arrays.asList(new Apple("green", 100)
                , new Apple("yellow", 300), new Apple("green", 200));
//        List<Apple> greenApple = findGreenApple(list);
//         System.out.println(yellowApple);

//        List<Apple> greenApple = findApple(list,"green");
//         System.out.println(yellowApple);
//        List<Apple> apple = findApple(list, new GreenAnd100WeightFilter());
//        System.out.println(yellowApple);
        List<Apple> yellowApple = findApple(list, apple -> ("yellow".equals(apple.getColor()) && apple.getWeight() == 300));
        System.out.println(yellowApple);
    }
}
